package com.hengshan.controller;


import com.hengshan.common.ResultBody;
import com.hengshan.common.annotation.SystemLog;
import com.hengshan.common.enums.BusinessType;
import com.hengshan.domain.LoginUser;
import com.hengshan.domain.entity.Role;
import com.hengshan.domain.entity.User;
import com.hengshan.domain.vo.PageVo;
import com.hengshan.service.impl.MenuServiceImpl;
import com.hengshan.service.impl.RoleServiceImpl;
import com.hengshan.service.impl.TokenService;
import com.hengshan.service.impl.UserServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 角色表(Role)表控制层
 *
 * @author muxijun
 * @since 2023-12-22 15:43:24
 */
@Validated
@RestController
@RequiredArgsConstructor
@RequestMapping("/system/role")
public class RoleController {

    private final RoleServiceImpl roleService;
    private final MenuServiceImpl menuService;
    private final UserServiceImpl userService;
    private final TokenService tokenService;
    public static final String MODULE_NAME = "角色管理";

    @SystemLog(title = MODULE_NAME, businessType = BusinessType.INSERT)
    @PostMapping({"/add"})
    public Role add(@Validated @RequestBody Role role) {
        return roleService.add(role);
    }

    @SystemLog(title = MODULE_NAME, businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public boolean update(@Validated @RequestBody Role role) {
        if (roleService.update(role)) {
            // 更新缓存用户权限
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            LoginUser loginUser = (LoginUser) authentication.getPrincipal();
            if (!loginUser.getUser().isAdmin()) {
                loginUser.setPermissions(menuService.selectPermsByUser(loginUser.getUser()));
                loginUser.setUser(userService.selectUserByUserName(loginUser.getUser().getUsername()));
                tokenService.setLoginUser(loginUser);
            }
            return true;
        }
        return false;
    }

    @SystemLog(title = MODULE_NAME, businessType = BusinessType.DELETE)
    @GetMapping("/delete/{id}")
    public ResultBody delete(@PathVariable("id") List<Integer> ids) {
        if (ids.contains(1)) {
            return ResultBody.fail("系统自带超级管理员角色不允许删除");
        }
        return ResultBody.success(roleService.deleteByIds(ids));
    }

    @GetMapping("/list")
    public PageVo<Role> list(@RequestParam int pageNum, @RequestParam int pageSize,
                             @RequestParam(required = false) String name, @RequestParam(required = false) String roleKey) {
        return roleService.getList(pageNum, pageSize, name, roleKey);
    }

    @GetMapping(value = {"/info/{id}", "/{id}"})
    public Role getInfo(@PathVariable(value = "id") Integer id) {
        return roleService.getOneById(id);
    }

    /**
     * 状态修改
     */
    @SystemLog(title = MODULE_NAME, businessType = BusinessType.UPDATE)
    @PostMapping("/changeStatus")
    public int changeStatus(@RequestBody Role role) {
        roleService.checkRoleAllowed(role);
        return roleService.updateRoleStatus(role);
    }

    /**
     * 查询已分配用户角色列表
     */
    @GetMapping("/authUser/allocatedList")
    public PageVo<User> allocatedList(@RequestParam int pageNum, @RequestParam int pageSize, @RequestParam int roleId,
                                      @RequestParam(required = false) String username, @RequestParam(required = false) String phone) {
        return userService.selectAllocatedList(pageNum, pageSize, roleId, username, phone);
    }

    /**
     * 查询未分配用户角色列表
     */
    @GetMapping("/authUser/unallocatedList")
    public PageVo<User> unallocatedList(@RequestParam int pageNum, @RequestParam int pageSize, @RequestParam int roleId,
                                        @RequestParam(required = false) String username, @RequestParam(required = false) String phone) {
        return userService.selectUnallocatedList(pageNum, pageSize, roleId, username, phone);
    }

    /**
     * 取消授权用户
     */
    @SystemLog(title = MODULE_NAME, businessType = BusinessType.GRANT)
    @PostMapping("/authUser/cancel")
    public boolean cancelAuthUser(@RequestBody Map<String, Object> map) {
        int roleId = (int) map.get("roleId");
        Long userId = Long.parseLong(map.get("userId").toString());
        return roleService.deleteAuthUser(roleId, userId);
    }

    /**
     * 批量取消授权用户
     */
    @SystemLog(title = MODULE_NAME, businessType = BusinessType.GRANT)
    @PostMapping("/authUser/cancelAll")
    public boolean cancelAuthUserAll(@RequestBody Map<String, Object> map) {
        int roleId = (int) map.get("roleId");
        String[] userIds = map.get("userIds").toString().split(",");
        return roleService.deleteAuthUsers(roleId, userIds);
    }

    /**
     * 批量选择用户授权
     */
    @SystemLog(title = MODULE_NAME, businessType = BusinessType.GRANT)
    @PostMapping("/authUser/selectAll")
    public boolean selectAuthUserAll(@RequestBody Map<String, Object> map) {
        int roleId = (int) map.get("roleId");
        String[] userIds = map.get("userIds").toString().split(",");
        return roleService.insertAuthUsers(roleId, userIds);
    }
}

